package com.example.seataordersys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.seataordersys.domain.Order;
import com.example.seataordersys.feign.AccountFeign;
import com.example.seataordersys.feign.StorageFeign;
import com.example.seataordersys.service.OrderService;
import com.example.seataordersys.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 *
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {


    @Autowired
    private AccountFeign accountFeign;
    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private StorageFeign storageFeign;

    @Override
    @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
    public void create(Long userId, Long productId, Integer count) {
        log.info("------->下单开始");
        Order ord = new Order();
        ord.setUserId(userId);
        ord.setProductId(productId);
        ord.setCount(count);
        BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
        ord.setMoney(orderMoney);
        ord.setStatus(0); //订单状态：0：创建中；1：已完结
        orderMapper.insert(ord);

        //远程调用库存服务扣减库存
        log.info("------->order-service中扣减库存开始");
        String storageRes = storageFeign.deduct(productId, count);
        log.info("------->order-service中扣减库存结束:{}",storageRes);

        //远程调用账户服务扣减余额
        log.info("------->order-service中扣减余额开始");
        String res = accountFeign.debit(userId, orderMoney);
        log.info("------->order-service中扣减余额结束:{}", res);

        //修改订单状态为已完成
        log.info("------->order-service中修改订单状态开始");
        ord.setStatus(1);
        orderMapper.updateById(ord);
        log.info("------->order-service中修改订单状态结束");

        log.info("------->下单结束");
    }


//    @Override
//    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
//    public void createOrder(Order order) {
//        log.info("------->下单开始");
//        //本应用创建订单
//        orderDao.create(order);
//
//        //远程调用库存服务扣减库存
//        log.info("------->order-service中扣减库存开始");
//        storageService.decrease(order.getProductId(),order.getCount());
//        log.info("------->order-service中扣减库存结束:{}",order.getId());
//
//        //远程调用账户服务扣减余额
//        log.info("------->order-service中扣减余额开始");
//        accountService.decrease(order.getUserId(),order.getMoney());
//        log.info("------->order-service中扣减余额结束");
//
//        //修改订单状态为已完成
//        log.info("------->order-service中修改订单状态开始");
//        orderDao.update(order.getUserId(),0);
//        log.info("------->order-service中修改订单状态结束");
//
//        log.info("------->下单结束");
//    }
}




